package sg.edu.nus.iss.team4.entity.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import sg.edu.nus.iss.team4.entity.dao.IBaseDAO;
import sg.edu.nus.iss.team4.entity.dao.PersistenceEntityBizException;

public class BaseDAOImpl<E, PK extends Serializable> implements IBaseDAO<E, PK> {

	private Class<E> entityType;
	private SessionFactory sessionFactory;

	public BaseDAOImpl(Class<E> entityType, SessionFactory sessionFactory) {
		this.entityType = entityType;
		this.sessionFactory = sessionFactory;
	}
	
	public void delete(E entity) {
		Session session = getSession();
		session.beginTransaction();
		session.delete(entity);
		session.getTransaction().commit();		
	}

	@SuppressWarnings("unchecked")
	public E findByPrimaryKey(PK pk) {
		Session session = getSession();
		session.beginTransaction();
		E persistentEntity = (E) session.get(entityType, pk); 
		session.getTransaction().commit();
		return persistentEntity;
	}

	@SuppressWarnings("unchecked")
	public E insert(E entity) {
		Session session = getSession();
		session.beginTransaction();
		E transientEntity = (E) session.save(entity); 
		session.getTransaction().commit();
		return transientEntity;
	}

	public void update(E entity) {
		Session session = getSession();
		session.beginTransaction();
		session.update(entity);
		session.getTransaction().commit();
	}

	public void insertAll(List<E> entities) {
		for (E entity : entities) {
			insert(entity);
		}
	}
	
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public List<E> findByPrimaryKey(E entity)
			throws PersistenceEntityBizException {
		// TODO Auto-generated method stub
		return null;
	}

}